import { asyncRoutes, constantRoutes } from '@/router'
import navigationApi from '@/api/navigation'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

// const actions = {
//   generateRoutes({ commit }, roles) {
//     return new Promise(resolve => {
//       let accessedRoutes
//       if (roles.includes('*')) {
//         accessedRoutes = asyncRoutes || []
//       } else {
//         accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
//       }
//       commit('SET_ROUTES', accessedRoutes)
//       resolve(accessedRoutes)
//     })
//   }
// }

const actions = {
  generateRoutes: async function({ commit }, roles) {
    let res = await navigationApi.getNavigation()
    debugger
    let myAsyncRoutes = encapsulationMenu(res.data.menus)
    myAsyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
    let accessedRoutes
    if (roles.includes('*')) {
      accessedRoutes = myAsyncRoutes || []
    } else {
      accessedRoutes = filterAsyncRoutes(myAsyncRoutes, roles)
    }
    console.log(accessedRoutes)
    commit('SET_ROUTES', accessedRoutes)
    return accessedRoutes
  }
}

const _import = require('./import-' + process.env.NODE_ENV);

export function encapsulationMenu(menus) {
  var router = []
  for (var i=0;i<menus.length;i++) {
    var data = menus[i]
    // 一级菜单
    var oneMenu = {}
    if (data.parentId === 0) {
      oneMenu = {
        path: data.menuPath,
        component: Layout,
        redirect: 'noRedirect',
        name: data.menuName,
        alwaysShow: true,
        meta: {
          title: data.menuTitle,
          icon: data.menuIcon,
          roles: data.perms
        }
      }
    } else {
      oneMenu = {
        path: data.menuPath,
        component: _import(`${data.menuUrl}`),
        name: data.menuName,
        meta: {
          title: data.menuTitle,
          roles: data.perms
        }
      }
    }
    if (data.children.length > 0) {
      var children = []
      for (var j =0;j<data.children.length;j++) {
        var menu = data.children[j]
        // 二级菜单
        var twoMenu = {
          path: menu.menuPath,
          component: _import(`${menu.menuUrl}`),
          name: menu.menuName,
          meta: {
            title: menu.menuTitle,
            roles: menu.perms
          }
        }
        if (menu.children.length > 0) {
          twoMenu.redirect = 'noRedirect'
          twoMenu.children = encapsulationMenu(menu.children)
        }
        children.push(twoMenu)
      }
      oneMenu.children = children
    }
    router.push(oneMenu)
  }
  return router
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
